package com.study.leetcode;

import java.util.HashMap;
import java.util.Map;

public class Solution_209 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> indexMap = new HashMap<>();
        int minStep = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            Integer index = indexMap.get(nums[i]);
            if (index == null) {
                indexMap.put(nums[i], i);
            } else {
                int step = i - index;
                if (step <= k) {
                    return true;
                }
                if (step < minStep) {
                    minStep = step;
                }
                indexMap.put(nums[i], i);
            }
        }
        return minStep <= k;
    }

    public static void main(String[] args) {
        Solution_209 solution209 = new Solution_209();
        int[] arr = {1, 2, 3, 1, 2,};
        boolean b = solution209.containsNearbyDuplicate(arr, 2);
        System.out.println("b = " + b);
    }
}
